$(document).ready(function(){
    $("#myform").validate({
        submitHandler: function(form)
        {
            do_add_new_control();
        }
    }
    );
    $('#selectItem').hide();
    $('#button_edit').hide();
});
//$(function () {
//    $('#file_upload').fileUploadUI({
//        uploadTable: $('#files'),
//        downloadTable: $('#files'),
//        buildUploadRow: function (files, index) {
//            return $('<tr><td>' + files[index].name + '<\/td>' +
//                '<td class="file_upload_progress"><div><\/div><\/td>' +
//                '<td class="file_upload_cancel">' +
//                '<button class="ui-state-default ui-corner-all" title="Cancel">' +
//                '<span class="ui-icon ui-icon-cancel">Cancel<\/span>' +
//                '<\/button><\/td><\/tr>');
//        },
//        buildDownloadRow: function (file) {
//            //alert(file.name);
//            //document.getElementById("avatar").src.value = file.name;
//            $("#avatar").attr("src",file.name);
//            $('#hidden_avatar').attr('value',file.name);
//
//        //return $('<tr><td><img src="' + file.name + '" width=60><\/td><\/tr>');
//        },
//        beforeSend: function (event, files, index, xhr, handler, callBack) {
//            var regexp = /\.(png)|(jpg)|(gif)$/i;
//            // Using the filename extension for our test,
//            // as legacy browsers don't report the mime type
//            if (!regexp.test(files[index].name)) {
//                handler.uploadRow.find('.file_upload_progress').html('ONLY IMAGES ALLOWED!');
//                setTimeout(function () {
//                    handler.removeNode(handler.uploadRow);
//                }, 10000);
//                return;
//            }
//            callBack();
//        }
//    });
//});

/*
 *@Author: Tri Nguyen
 *@Function: Uploadify
 *
 */


function updateCCA1(){
    oFormObject = document.forms['myform'];
    oFormObject.elements["cca_fee[1]"].value = '0.00';
}
function updateCCA2(){
    oFormObject = document.forms['myform'];
    oFormObject.elements["cca_fee[2]"].value = '0.00';
}

var errorValue = Array();

function isMoney(field){
    var check = true;
    //    var value = field.value; //get characters
    //
    //    var inV = parseInt(value);
    //
    //    if (inV == "NaN")
    //        check = false;
    //    else
    //    if (inV < 0)
    //        check = false;
    //    else
    //        //check that all characters are digits, ., -, or ""
    //        for(var i=0;i < field.value.length; ++i)
    //        {
    //            var new_key = value.charAt(i); //cycle through characters
    //            if(((new_key < "0") || (new_key > "9")) &&
    //                !(new_key == "") || (new_key == '-') && (new_key == '.')){
    //                check = false;
    //                break;
    //            }
    //        }

    var ValidChars = "0123456789.";
    var Char;


    for (i = 0; i < field.value.length && check == true; i++)
    {
        Char = field.value.charAt(i);
        if (ValidChars.indexOf(Char) == -1)
        {
            check = false;
            break;
        }
    }

    if (errorValue.indexOf(field) >= 0)
    {
        errorValue[errorValue.indexOf(field)] = errorValue[0];
        errorValue.shift();
    }
    //apply appropriate colour based on value
    if(!check)
    {
        field.style.backgroundColor = "red";
        errorValue.push(field);
    //field.value = "0";
    // alert("The money input is not validate");
    }
    else
    {
        field.style.backgroundColor = "white";
    }
}

function checkform()
{
    if (errorValue.length >0)
    {
        alert("The input value are incorect.");
        errorValue[0].focus();
        return false;
    }
    return true;
}



function createDropdown(value){
    $('#button_add').fadeIn();
    $('#button_edit').fadeOut();
    $('.txtName-en').val('');
    $('.txtName-cn').val('');
    if(value == 6 || value == 1 || value == 5){
        $('#selectItem').fadeIn();
        $('.selectItem_div').html('');
        $('#selectItem_div_label').fadeIn();
    }else{
        $('#selectItem').hide();
        $('.selectItem_div').hide();
        $('#selectItem_div_label').fadeOut();
    }
}

function cancelUpdate()
{
    createDropdown(0);
    $("#cboControl").val(0);
}

/* Begin add and deleted new item */
function add_value(){
    var id = $('#value_item_new').val();
    var html = '';
    var randomnumber=Math.floor(Math.random()*1100)
    html += '<div class="selectItem">';
    html += '<input type="text" class="pos_new_'+id+' valueItem-en new myrequired" size="10" name="new' + randomnumber + '" id="new' + randomnumber + '"/>';
    randomnumber=Math.floor(Math.random()*1100)
    html += '<input type="text" class="pos_new_'+id+' valueItem-cn new myrequired" size="10" name="new' + randomnumber + '" id="new' + randomnumber + '"/>';
    html += '<a class="pos_new_'+id+'" href="javascript:void(0)" onclick="delete_item_new('+id+')">Delete</a>';
    html += '</div>';
    var the_class = '.pos_new_'+id;
    $('.selectItem_div').append(html);
    $('.selectItem_div').fadeIn();
    $('#selectItem_div_label').fadeIn();
    $(the_class).rules('add',{
        required: true
    });
    id = parseInt(id) + 1;
    $('#value_item_new').val(id);
}

function delete_item_new(id){
    var pos_id = '.pos_new_'+id;
    $(pos_id).remove();
    //$(pos_id).fadeOut();
    //$(pos_id).attr('class','deleted');
}
/* End add and deleted new item */


/* Begin add and deleted new control*/

function do_add_new_control()
{
    var label_en = $('.txtName-en').val();
    var label_cn = $('.txtName-cn').val();
    var control = $('#cboControl').val();
    var tab = $('#value_tab').val();
    var value_en = Array();
    var value_cn = Array();
    if(control == 6 || control == 1 || control == 5){
        $(".valueItem-en").each(function() {
            value_en.push($(this).val())
        });
        $(".valueItem-cn").each(function() {
            value_cn.push($(this).val())
        });
    }

    var id = $('#value_item').val();
    $.ajax({
        type: 'POST',
        url: SITE_URL+'/custom_field/add_new_control',
        data: {
            'label_en':label_en,
            'label_cn':label_cn,
            'control':control,
            'tab': tab,
            'id': id,
            'value_en[]':value_en,
            'value_cn[]':value_cn
        },
        success: function(data){
            $('.txtName-en').val('');
            $('.txtName-cn').val('');                        
            $('#list_item_dynamic').append(data).fadeIn();
            id = parseInt(id) + 1;            
            $('.txtName-en').val('');
            $('.txtName-cn').val('');
            $('.valueItem-en').val('');
            $('.valueItem-cn').val('');
            $('a[class*=new]').hide();
            $('input[class*=new]').hide();
            $('input[class*=new]').attr('class','deteled');
            $('#selectItem').hide();
            $('#value_item').val(id);
            $('#cboControl').val(7);
        }
    })
}

function add_new_control(){
    var err = 0;
    $("#errorMess").html('');
    $("#manage_control input").each(function(){
        if ($(this).val() == '' && $(this).attr('type') == 'text' && $(this).hasClass("new"))
        {
            $("#errorMess").html(jQuery.validator.messages['required']);
            err = 1;
            $(this).addClass("error");
        }
        else
            $(this).removeClass("error");
    });

    if ($('#selectItem_div_label').css('display') != 'none' && $(".selectItem_div input.new").length ==0)
    {
        add_value();
        add_new_control();
        return;
    }

    if (err == 0)
        $('#myform').submit();
}

function delete_item(id){
    var pos_id = '#pos_'+id;
    var control_id = '.control_'+id;
    var label_en = $(control_id + ".label_en").val();
    if(!confirm('Do you want to delete this field.\nAll children <'+label_en+'> info will be also deleted?')){
        return;
    }
    $(pos_id).fadeOut();
    $(control_id).attr('name','deleted');
    $.ajax({
        type: 'POST',
        url: SITE_URL+'/custom_field/delete_customfield',
        data: 'id='+id,
        success: function(data){
            if(data == 1){
                alert('Successful!');
            }else{
                alert('Fail');
            }
        }
    })

}

function edit_item(id){
    $('#update_id').val(id);
    var the_class = '.control_'+id;
    var control = $(the_class+'.type').val();
    var value_en = Array();
    var value_cn = Array();
    var value_id = Array();
    var label_cn = '';
    var label_en = '';
    var html = '';

    $("#cboControl").val(control);
    var order_id = $('#value_item_new').val();
    $(the_class+'.value_id').each(function(){
        value_id.push($(this).val());
    });
    $(the_class + ".option_en").each(function() {
        value_en.push($(this).val())
    });
    $(the_class + ".option_cn").each(function() {
        value_cn.push($(this).val())
    });
    $(the_class + ".label_en").each(function() {
        label_en = $(this).val();
    });
    $(the_class + ".label_cn").each(function() {
        label_cn = $(this).val();
    });
    for(var i=0;i<value_en.length;i++){
        html += '<div class="selectItem">';
        html += '<input type="text" class="pos_new_'+order_id+' valueItem-en new" value="'+value_en[i]+'" size="10" /> <input type="text" class="pos_new_'+order_id+' valueItem-cn new" value="'+value_cn[i]+'" size="10" /><a class="pos_new_'+order_id+'" href="javascript:void(0)" onclick="delete_item_new('+order_id+')">Delete</a>';
        html += '<input type="hidden" class="pos_new_'+order_id+' valueItem_id" value="'+value_id[i]+'" />';
        html += '</div>';
        order_id = parseInt(order_id) + 1;
    }
    $('#value_item_new').val(order_id);
    $('.txtName-en').val(label_en);
    $('.txtName-cn').val(label_cn);
    $('#button_edit').fadeIn();
    $('#button_add').fadeOut();
    if(html != ''){
        $('#selectItem').fadeIn();
        $('.selectItem_div').html(html);
        $('.selectItem_div').fadeIn();
        $('#selectItem_div_label').fadeIn();
    }else{
        $('#selectItem').fadeOut();
        $('.selectItem_div').fadeOut();
        $('#selectItem_div_label').fadeOut();
    }
}

function update_control(){
    var id = $('#update_id').val();
    var label_en = $('.txtName-en').val();
    var label_cn = $('.txtName-cn').val();
    var control = $('#cboControl').val();
    var tab = $('#value_tab').val();
    var value_en = Array();
    var value_cn = Array();
    var value_id = Array();
    $(".valueItem_id").each(function() {
        value_id.push($(this).val())
    });
    $(".valueItem-en").each(function() {
        value_en.push($(this).val())
    });
    $(".valueItem-cn").each(function() {
        value_cn.push($(this).val())
    });
    $.ajax({
        type: 'POST',
        url: SITE_URL+'/custom_field/update_customfield',
        data: {
            'label_en':label_en,
            'label_cn':label_cn,
            'control':control,
            'tab': tab,
            'id': id,
            'value_en[]':value_en,
            'value_cn[]':value_cn,
            'value_id[]':value_id
        },
        success: function(data){            
            $('.txtName-en').val('');
            $('.txtName-cn').val('');
            location.reload();
        //            $('#list_item_dynamic').append(data).fadeIn();
        //            $('.txtName-en').val('');
        //            $('.txtName-cn').val('');
        //            $('.valueItem-en').val('');
        //            $('.valueItem-cn').val('');
        //            $('a[class*=new]').hide();
        //            $('input[class*=new]').hide();
        //            $('input[class*=new]').attr('class','deteled');
        //            $('#selectItem').hide();
        //            $('#cboControl').val(7);
        }
    })
}
/* End add and deleted new control*/